import { defineStore } from "pinia";
import { computed, ref } from "vue";
import { useUserStore } from "./user";
import { insertCartAPI,findNewCartListAPI,delCartAPI } from "@/apis/cart";
export const useCartStore=defineStore('cart',()=>{
  const userStore=useUserStore();
  let isLogin=computed(()=>{
    return userStore.userInfo.token;
  })

  let cartList=ref([]);
  async function addCart(good){
    // console.log(isLogin.value);
    const {skuId,count}=good;
    if(isLogin.value){
      await insertCartAPI({skuId,count});
      updateNewList();
    }
    else{
      const item= cartList.value.find((arr)=>{
        if(arr.skuId===good.skuId){
          return true;
        }
        else{
          return false;
        }
      })
      if(item){
        item.count++;
      }
      else{
        cartList.value.push(good);
      }
    }
    // console.log(data);

    // console.log(cartList.value);
  }
  async function delCart(skuId){
    if(isLogin.value){
      await delCartAPI([skuId]);
      updateNewList();
    }
    else{

    }
    cartList.value= cartList.value.filter((item)=>{
      if(item.skuId==skuId){
        return false;
      }
      return true;
    })
  }
async function updateNewList(){
  let res=await findNewCartListAPI();
  cartList.value=res.result;
}

  let allCount= computed(()=>{
    return cartList.value.reduce((pre,item)=>{
      return pre+item.count;
    },0)
  })
  let allPrice=computed(()=>{
    return cartList.value.reduce((pre,item)=>{
      return pre+item.count*item.price;
    },0)
  },)
  // console.log(allCount.value);
  // console.log(allPrice.value);
  function singleCheck(skuId,selected){
    let item=cartList.value.find((arr)=>{
      if(arr.skuId==skuId){
        return true;
      }
      return false;
    })
    item.selected=selected;
  }
  let isAll=computed(()=>{
    return cartList.value.every((item)=>{
      return item.selected;
    })
  })
  function allCheck(selected){
    cartList.value.forEach((item)=>{
      item.selected=selected;
    })
  }
  let selectedCount=computed(()=>{
    return cartList.value.reduce((pre,item)=>{
      if(item.selected){
        return pre+item.count;
      }
      else{
        return pre;
      }
    },0)
  });
  let selectedPrice=computed(()=>{
    return cartList.value.reduce((pre,item)=>{
      if(item.selected){
        return pre+item.count*item.price;
      }
      else{
        return pre;
      }
    },0)
  })
  function clearCart(){
    cartList.value=[];
  }
  return{
    cartList,
    allCount,
    allPrice,
    isAll,
    selectedCount,
    selectedPrice,
    addCart,
    delCart,
    singleCheck,
    allCheck,
    clearCart,
    updateNewList,
  }
},{
  persist: true,
})
